/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019.
 * Description: fiq_glue_setup.c
 * Author: xiekunxun <xiekunxun@huawei.com>
 * Create: 2013-04-07
 */

#include <linux/kernel.h>
#include <linux/percpu.h>
#include <linux/slab.h>
#include <linux/hal/fiq_glue.h>
#include <asm/fiq.h>
#include "../../fiq_glue_com/fiq_glue_private.h"

static struct fiq_handler fiq_debbuger_fiq_handler = {
	.name = "fiq_glue",
};
static DEFINE_PER_CPU(void *, fiq_stack) = {NULL};
static struct fiq_glue_handler *current_handler;
static DEFINE_MUTEX(fiq_glue_lock);

static void fiq_glue_setup_helper(void *info)
{
	struct fiq_glue_handler *handler = info;
	int cpu = raw_smp_processor_id();

	fiq_glue_setup(handler->fiq, handler,
			per_cpu(fiq_stack, cpu) + THREAD_START_SP);
}

static inline int fiq_stack_alloc(void)
{
	int cpu;
	void *stack;

	for_each_possible_cpu(cpu) {
		stack = (void *)__get_free_pages(GFP_KERNEL, THREAD_SIZE_ORDER);
		if (WARN_ON(!stack)) {
			printk(KERN_ERR"%s, %d", __func__, __LINE__);
			return -ENOMEM;
		}
		printk("addr%d, %pK\n", cpu, stack);
		per_cpu(fiq_stack, cpu) = stack;
	}

	printk("fiq_stack init ok\n");
	return 0;
}

static inline void fiq_stack_free(void)
{
	int cpu;

	for_each_possible_cpu(cpu) {
		if (per_cpu(fiq_stack, cpu) != NULL) {
			__free_pages(per_cpu(fiq_stack, cpu), THREAD_SIZE_ORDER);
			per_cpu(fiq_stack, cpu) = NULL;
		}
	}
}

int fiq_glue_register_handler(struct fiq_glue_handler *handler)
{
	int ret;
	unsigned char *start;

	if (!handler || !handler->fiq)
		return -EINVAL;

	mutex_lock(&fiq_glue_lock);
	if (per_cpu(fiq_stack, 0)) {
		printk(KERN_ERR"already registered\n");
		current_handler = handler;
		on_each_cpu(fiq_glue_setup_helper, handler, true);
		goto out;
	}

	ret = fiq_stack_alloc();
	if (ret)
		goto err_alloc_fiq_stack;

	ret = claim_fiq(&fiq_debbuger_fiq_handler);
	if (WARN_ON(ret)) {
		printk(KERN_ERR"claim fiq failed\n");
		goto err_claim_fiq;
	}

	current_handler = handler;
	on_each_cpu(fiq_glue_setup_helper, handler, true);
	/* address of vector_fiq_glue may not be aligned, so we align by 4 bytes */
	start = (unsigned char *)ALIGN((unsigned int)&vector_fiq_glue, 4);
	if (&vector_fiq_glue_end - start > 0x200-0x1c) {
		printk(KERN_ERR"code too long!\n");
		ret = -E2BIG;
		goto err_code_out_of_range;
	}
	set_fiq_handler(start, &vector_fiq_glue_end - start);

out:
	mutex_unlock(&fiq_glue_lock);
	printk("%s, ok", __func__);

	return 0;

err_code_out_of_range:
err_claim_fiq:
err_alloc_fiq_stack:
	fiq_stack_free();
	mutex_unlock(&fiq_glue_lock);
	printk(KERN_ERR"%s, %d, failed", __func__, __LINE__);
	return ret;
}

